package scau.zxck.dao;

import scau.zxck.utils.NameUtil;
import scau.zxck.constant.ERROR;
import scau.zxck.entity.ColumnInfo;
import scau.zxck.entity.TableInfo;
import scau.zxck.exception.BaseException;
import scau.zxck.utils.PropUtil;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lsp on 27/11/2016.
 */
public class TableInfoDao {
    private Connection conn;

    public TableInfoDao(Connection conn) {
        this.conn = conn;
    }

    public List<TableInfo> getTableInfo() throws BaseException {
        List<TableInfo> tableInfoList = new ArrayList<TableInfo>();
        try {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet rs = metaData.getTables(null, null, null, new String[]{"TABLE"});
            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME");
                TableInfo tableInfo = new TableInfo();
                tableInfo.setTableName(tableName);
                tableInfo.setClazzName(NameUtil.specialUnderlineToCapitalizeCamel(tableName));
                tableInfoList.add(tableInfo);
            }
        } catch (SQLException e) {
            throw new BaseException(ERROR.QUERY_TABLE_ERROR, e);
        }
        return tableInfoList;
    }

    public List<ColumnInfo> getColumnInfo(TableInfo tableInfo) throws BaseException {
        List<ColumnInfo> columnInfoList = new ArrayList<ColumnInfo>();
        try {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet rs = metaData.getColumns(null, "%", tableInfo
                    .getTableName(), "%");
            while (rs.next()) {
                String columnName = rs.getString("COLUMN_NAME");
                if("id".equals(columnName)){
                    continue;
                }

                String columnType = rs.getString("TYPE_NAME");
                String fieldName = NameUtil.underlineToCamel(columnName);
                String fieldType = PropUtil.getTypeProp(columnType);

                if (null == fieldType) {
                    throw new BaseException(ERROR.TRANSFER_TYPE_ERROR);
                }

                ColumnInfo columnInfo = new ColumnInfo();
                columnInfo.setColumnName(columnName);
                columnInfo.setColumnType(columnType);
                columnInfo.setFieldName(fieldName);
                columnInfo.setFieldType(fieldType);
                columnInfoList.add(columnInfo);
            }
        } catch (SQLException e) {
            throw new BaseException(ERROR.QUERY_COLUMN_ERROR, e);
        }
        return columnInfoList;
    }
}
